#include <QImage>
#include <QMessageBox>
#include <QInputDialog>
#include <QStringList>
#include <QBitmap>
#include <QLabel>
#include <QPushButton>
#include <QPixmap>
#include <klineedit.h>
#include <ktextedit.h>
#include <kdialog.h>
#include <kpagedialog.h>
#include <cstdio>

#include "screen.h"
#include "global.h"

// um...until we get a way to share the declaration of keygrps, I'll just include this here for the sake of having a convenient and potentially smal  way (once I remove this stuff) of detecting keypresses via mouse

void screen::paintEvent(QPaintEvent*){
  QPainter painter(this);
  //calc_run_frame(calc);
  //uint8_t* image=calc_draw(calc);
  
	calc_run_frame(calc);
  //uint8_t* image=calc_draw(calc); ?
  
  //CPU_t *cpu = &calcs[calc].cpu;
  //uint8_t* image=LCD_image(cpu->pio.lcd);
  uint8_t* image=calc_draw(calc);
 
  QImage* LCD = new QImage((unsigned char*)image,128,64,128,QImage::Format_Indexed8);
  LCD->setColorTable(colorVector);
  QImage copy(LCD->copy(-2,0,98,64));
  if(drawSkin){
    QImage scaled(copy.scaledToWidth(196));
    painter.drawImage(62,74,scaled,QImage::Format_Indexed8);
  }
  else{
    //int zoomAmount=zoom*96; // Because the compiler complains otherwise...
    QImage scaled(copy.scaledToWidth((int)(zoomAmount*96)));
    painter.drawImage(0,0,scaled,QImage::Format_Indexed8);
  }
//painter.drawImage(62,74,*LCD,QImage::Format_Indexed8);


  if(gifCaptureRunning){
    gdImagePtr im2=gdImageCreateFromWBMPPtr(64*96,LCD->bits());
   copy.save("frame.png");
    //gdImagePtr im2=gdImageCreate(96,64);
    /*
  int black = gdImageColorAllocate(im2, 0, 0, 0);
    gdImageRectangle(im2, 0, 0, 10, 10, black);
    gdImageGifAnimAdd(im2,gifout,1,0,0,4,gdDisposalNone, NULL);
    int white = gdImageColorAllocate(im2, 255, 255, 255);
   gdImageRectangle(im2, 0, 0, 10, 10, white);
  */
  
  FILE *in;
  in = fopen("frame.png", "rb");
  im2 = gdImageCreateFromPng(in);
  gdImageGifAnimAdd(im2,gifout,1,0,0,2,gdDisposalNone, NULL);
   // Change LocalCM and adjust delay
  fclose(in);
  gdImageDestroy(im2);
  } 
}

void screen::menuRequested(const QPoint &position){
  QPoint globalPos = this->mapToGlobal(position);
  menu->exec( globalPos );
}

void screen::sendFile(){
  QStringList fileNames = QFileDialog::getOpenFileNames(gWin, "WabbitEmu: Please select a file","/","Known file types (*.8xc *.8xd *.8xi *.8xl *.8xm *.8xn *.8xp *.8xs *.8xt *.8xw *.8xy *.8xz);;All files (*.*)");  // TODO: find other valid types
  if(fileNames.count()){ // Is this the right condition for a QStringList?
    int a,b;
    int length=0;
    // inefficient much? TODO...
    for(a=0;a<fileNames.count();a++)
      for(b=0;b<=fileNames[a].length();b++)
	length++;
    char* array_fileNames=(char*)malloc(length);
    char* ptr_fileNames=array_fileNames;
    for(a=0;a<fileNames.count();a++){
      QByteArray ba_fileName=fileNames[a].toLatin1();
      memcpy(ptr_fileNames,ba_fileName.data(),ba_fileName.length()+1);
      ptr_fileNames+=ba_fileName.length()+1;
    }
    
   // QByteArray ba_fileName = fileName.toLatin1();
    // const char *c_fileName = ba_fileName.data(); 
   // const char* c_fileName = "/home/bfr/SB.8xp";
 // char* var_fileName=(char*)c_fileName;
NoThreadSend(array_fileNames,SEND_RAM); // is the second argument correct..?
//SendFile(c_fileName,SEND_RAM);
      /*
      TIFILE_t *tifile = importvar(filename);
      sendvar(calc, tifile, SEND_CUR);
      FreeTiFile(tifile);
    */
      //TIFILE_t * tiFile=importvar(c_fileName);
    //SendFile(const_cast<char*>(c_fileName),1 );
     // ...or something
  }
}
void screen::sound(){
}
void screen::enterDebugger(){
}
void screen::loadState(){
  fileName = QFileDialog::getOpenFileName(gWin, "WabbitEmu: Please select a ROM","/","Known file types (*.rom *.sav);;All files (*.*)"); 
  if(!fileName.isNull()){
      settings->setValue("options/rom",fileName);
      QByteArray ba_fileName = fileName.toLatin1();
      char *c_fileName = ba_fileName.data(); 
      rom_load(calc, c_fileName);
  }
}
void screen::saveState(){
  uint8_t* image=Qt_savestate_init(calc);
fileName = QFileDialog::getSaveFileName(gWin, "WabbitEmu: Please name a ROM","/","Known file types (*.rom *.sav);;All files (*.*)"); 
if(!fileName.isNull()){
  QByteArray ba_fileName = fileName.toLatin1();
  char *c_fileName = ba_fileName.data(); 
// Messy, but hopefully a pretty quick way to do this..
KDialog* saveStateInfo = new KDialog;
KLineEdit* authorEdit = new KLineEdit(saveStateInfo);
KTextEdit* commentEdit = new KTextEdit(saveStateInfo);
QLabel* authorLabel = new QLabel("Author",saveStateInfo);
QLabel* commentLabel = new QLabel("Comment",saveStateInfo);
//QPushButton* okButton = new QPushButton("OK",saveStateInfo);
//QPushButton* cancelButton = new QPushButton("Cancel",saveStateInfo);
QLabel* previewLabel = new QLabel(saveStateInfo);
QPixmap previewBox;
QLabel* modelLabel = new QLabel("Model",saveStateInfo);
QLabel* romVersionLabel = new QLabel("ROM version",saveStateInfo);
QLabel* fileSizeLabel = new QLabel("Filesize",saveStateInfo);
QLabel* modelVal = new QLabel(saveStateInfo);
QLabel* romVersionVal = new QLabel(saveStateInfo);
QLabel* fileSizeVal = new QLabel(saveStateInfo);
saveStateInfo->setButtons( KDialog::Ok | KDialog::Cancel);
saveStateInfo->resize(354, 286);
authorEdit->setGeometry(90, 120, 146, 26);
commentEdit->setGeometry(90, 170, 256, 71);
authorLabel->setGeometry(10, 120, 61, 18);
commentLabel->setGeometry(10, 170, 71, 18);
previewLabel->setGeometry(10, 10, 151, 101);
modelLabel->setGeometry(170, 20, 61, 18);
romVersionLabel->setGeometry(170, 50, 81, 18);
fileSizeLabel->setGeometry(170, 80, 61, 18);
modelVal->setGeometry(270, 20, 61, 18);
romVersionVal->setGeometry(270, 50, 61, 18);
fileSizeVal->setGeometry(270, 80, 61, 16);
modelVal->setText(QString(Qt_calcModel(calc)));
QString* romVersion = new QString;
//romVersion->setNum(Qt_calcRomVersion(calc));
romVersionVal->setText(QString(Qt_calcRomVersion(calc)));
//okButton->setGeometry(150, 250, 91, 28);
//cancelButton->setGeometry(250, 250, 91, 28);
  // TODO: optimize, this code is repeated from LCD drawing
QImage* LCD = new QImage((unsigned char*)image,128,64,128,QImage::Format_Indexed8);
  LCD->setColorTable(colorVector);
  QImage copy(LCD->copy(-2,0,98,64));
previewBox = QPixmap::fromImage(copy.scaledToWidth(151));
previewLabel->setPixmap(previewBox);
saveStateInfo->setButtonsOrientation(Qt::Horizontal);
saveStateInfo->update();
if(saveStateInfo->exec())
{
QString str_author = authorEdit->text();
QByteArray ba_author = str_author.toLatin1();
char *author= ba_author.data();
QString str_comment = commentEdit->toPlainText();
QByteArray ba_comment = str_comment.toLatin1();
char *comment= ba_comment.data();
//char author[32]={'S','o','m','e','b','o','d','y',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
//char comment[64]={'T','e','s','t',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
	
Qt_savestate_save(c_fileName,author,comment);

}
else{
saveStateInfo->close();
}
Qt_savestate_free();
//char* author = "Somebody"; // for now..
 // char* comment = "WabbitEmu save state";
//SAVESTATE_t *savestate=CreateSave(author, comment , 2);
//LCD_t lcd;
//LoadLCD(savestate, &lcd);
//SAVESTATE_t *savestate=SaveSlot(calc);
//WriteSave(c_fileName, savestate, 0);
//FreeSave(savestate);
  //char* author = "Somebody"; // for now..
  //char* comment = "WabbitEmu save state";
 // WriteSave(c_fileName,CreateSave(author, comment , 2),0);
}
}
void screen::reloadLastState(){
}
void screen::resetCalculator(){
  //calc_reset(calc);
  //Qt_calc_reset(calc);
}
void screen::startGIFCapture(){
  gifCaptureRunning=1-gifCaptureRunning;
  if(!gifCaptureRunning){
    //putc (';', gifout);
    gdImageGifAnimEnd(gifout);
    QMessageBox::information ( 0, "Gif Capture Stopped", "Outputted screenshot as gifout.gif in current directory");
  }
  else{
    gdImageGifAnimBegin(im,gifout,1,0);
  }
}
void screen::skinLess(){
}
/*
void screen::zoom(short amount){
}
*/
void screen::copyANSToClipboard(){
}
void screen::options(){
 
 //gApp->disconnect( timer, SIGNAL( timeout() ), 0,0);
KPageDialog* options  = new KPageDialog(gWin);
  options->setParent(gWin);
   options->setFaceType(KPageDialog::Tabbed);
   options->addPage(this,"Display");
   options->addPage(this,"ROM");
   options->exec();
//gApp->connect( timer, SIGNAL( timeout() ),this, SLOT( update() ) );
/*
SendMessage(edtRom_path, WM_SETTEXT, 0, (LPARAM) calcs[SlotSave].rom_path);
			SendMessage(edtRom_version, WM_SETTEXT, 0, (LPARAM) calcs[SlotSave].rom_version);
			SendMessage(edtRom_model, WM_SETTEXT, 0, (LPARAM) CalcModelTxt[calcs[SlotSave].model]);
			char szRomSize[16];
			sprintf(szRomSize, "%0.1f KB", (float) calcs[SlotSave].cpu.mem_c->flash_size/1024.0f);
*/
}
void screen::visitWebsite(){
  // who DOESN'T use firefox? TODO.  use webkit thing and open in custom browser?
  system("firefox http://www.revsoft.org/phpBB2/viewforum.php?f=32");
}
void screen::exitEmulator(){
  calc_free(calc);
  
  settings->setValue("options/zoom",zoomAmount);
  settings->setValue("options/drawSkin",drawSkin);
  settings->sync();
  fclose(gifout);
  gdImageDestroy(im);
  
  gApp->quit();
}
void screen::exitSaveEmulator(){
  calc_free(calc);
  settings->setValue("options/zoom",zoomAmount);
  settings->setValue("options/drawSkin",drawSkin);
  settings->sync();
  fclose(gifout);
  gdImageDestroy(im);
  gApp->quit();
}

void screen::recordKeyMacro(){
  macroRunning=1-macroRunning;
  if(macroRunning){
    QMessageBox::information ( 0, "Key Recording Started", "Press CTRL R or the Start/Stop Recording menu option to stop recording");
  }
  else{

  }
  /*
if(!macroRunning){
    QString macroName = QInputDialog::getText ( gWin, "Enter Macro Name", "Name");
    QList<keyMacro> macroNames;
    // Put all of the existing macros in a list, then append the new one, then write them all...seems inefficient, but... 
    int size = settings->beginReadArray("keyMacros");
    for (int i = 0; i < size; ++i) {
      settings->setArrayIndex(i);
      keyMacro entry;
      entry.name = settings->value("name").toString();
      QVariantList temp=settings->value("keys").toList()
      int c;
      for(c=0;c<temp.size();c++){ // C++ ftw
	temp.Qconvert(QVariant::Int);
      macroNames.append(entry);
    }
    settings->endArray();
 
    keyMacro newMacro;
    newMacro.keys=mkeys;
    newMacro.name=macroName;
    macroNames.append(newMacro);
 
    settings->beginWriteArray("keyMacros");
    for (int i = 0; i < macroNames.size(); i++) {
     settings->setArrayIndex(i);
     settings->setValue("name", macroNames[i].name);
     settings->setValue("keys", macroNames[i].keys);
    }
    settings->endArray();
  }
*/

}

void screen::runKeyMacro(){
  /*
  int size = settings.beginReadArray("keymacros");
  QList<QAction> runKeyMacros;
  QList<QAction> deleteKeyMacros;
  for (int i = 0; i < size; i++) {
    settings.setArrayIndex(i);
    QAction macro(settings.value("name"),menu);
    keyMacros.append(macro);
    deleteKeyMacros.append(macro);
    Run->addAction(keyMacros.last());
    Delete->addAction(deleteKeyMacros.last());
    app.connect (keyMacros, SIGNAL ( triggered() ) ), screenimpl, SLOT ( menuRequested(const QPoint &) ));
     
  settings->endArray();
*/
  
}

void screen::deleteKeyMacro(){
}

void screen::viewKeyMacros(){
}
